package com.redstar.HappyRefresh.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
public class JwtUtils {

    private static final int expirationTime = 365; // 365天后过期
    private static final String secretKey = "7b529cd8-8b7b-43bc-9c62-aa47d757cada"; // 秘钥

    public static String getToken(Long userId, String nickname) { // 生成token
        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("user")
                .setIssuedAt(new Date())
                .setExpiration(DateUtil.addDateDays(new Date(), expirationTime))
                .claim("id", userId)
                .claim("nickname", nickname)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
        log.info("生成的token为：{}", token);
        return token;
    }

    public static boolean checkToken(HttpServletRequest request) { // 检查请求头中是否携带token
        try {
            String token = request.getHeader("token");
            if (!StringUtils.hasLength(token)) {
                return false;
            }
        } catch (Exception e) {
            log.error("从请求头中取出token发生异常：{}", e.getMessage());
            return false;
        }
        return true;
    }

    public static Long getUserId(HttpServletRequest request) { // 从请求头中取出userId
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Long userId = Long.valueOf(claims.get("id").toString());
        // 检查token是否过期
        Date expiration = claims.getExpiration();
        if (expiration.before(new Date())) {
            return null; // 如果已过期，返回null
        }
        return userId;
    }
}
